package juc;

public class TestProductorAndConsumer {
    public static void main(String[] args) {
        Market market = new Market();
        new Thread(new Productor(market), "生产者1").start();
        new Thread(new Productor(market), "生产者2").start();
        new Thread(new Consumer(market), "消费者").start();
    }
}


class Market {
    int product;

    public synchronized void get() {
        while (product >= 10) {
            System.out.println("商品已满！");
            try {
                this.wait();
            } catch (InterruptedException e) {
            }
        }
        System.out.println(Thread.currentThread().getName() + ",生产了商品:" + ++product);
        this.notifyAll();

    }

    public synchronized void send() {
        while (product <= 0) {
            System.out.println("商品已卖完！");
            try {
                this.wait();
            } catch (InterruptedException e) {
            }
        }
        System.out.println(Thread.currentThread().getName() + ",消费了商品:" + --product);
        this.notifyAll();

    }
}

class Productor implements Runnable {
    Market market;

    public Productor(Market market) {
        this.market = market;
    }

    @Override
    public void run() {
//        for (int i = 0; i < 20; i++) {
        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            market.get();
        }
    }
}

class Consumer implements Runnable {
    Market market;

    public Consumer(Market market) {
        this.market = market;
    }

    @Override
    public void run() {
//        for (int i = 0; i < 20; i++) {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            market.send();
        }
    }
}